// DynamicWaveFormView.java
package com.example.blue.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ConcurrentLinkedQueue;

public class DynamicWaveFormView extends View {
    private static final int MAX_POINTS = 200; // 总共显示500个点 (10秒数据)
    private static final int UPDATE_INTERVAL = 20; // 更新间隔20ms

    private List<Float> dataPoints = new ArrayList<>();
    private final ConcurrentLinkedQueue<Float> dataQueue = new ConcurrentLinkedQueue<>();

    private List<Long> timeStamps = new ArrayList<>();
    private Paint gridPaint;
    private Paint wavePaint;
    private Paint textPaint;
    private Paint axisPaint;
    private Paint verticalTitlePaint;
    private String yzhouTitle;
    private Integer maxYvalue;
    private Integer minYvalue;
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
    private int bottonPixel;
    private int topPixel;
    private static final int paddingTop = 30; // 上边距
    private static final int paddingLeft = 100; // 左边距
    private static final int paddingRight = 20; // 右边距
    private static final int paddingBottom = 60; // 下边距（为时间标签留空间）
    private int chartWidth;
    private int chartHeight;
    public DynamicWaveFormView(Context context) {
        super(context);
        init();
    }

    public DynamicWaveFormView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        post(updateRunnable); // 开始定时刷新
    }
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        removeCallbacks(updateRunnable); // 停止刷新，避免内存泄漏
    }
    // 定时刷新 Runnable
    private final Runnable updateRunnable = new Runnable() {
        @Override
        public void run() {
            Float value;
            while ((value = dataQueue.poll()) != null) {
                addPointInternal(value);
            }
            invalidate();
            postDelayed(this, UPDATE_INTERVAL); // 30ms 刷新一次
        }
    };
    private void addPointInternal(float value) {

        dataPoints.add(value);
        timeStamps.add(System.currentTimeMillis());
        if (dataPoints.size() > MAX_POINTS) {
            dataPoints.remove(0); // 滚动效果
            timeStamps.remove(0);
        }
    }
    public static int[] getViewTopAndBottom(View view) {
        int[] result = new int[2];

        if (view == null) return result;

        int[] location = new int[2];
        view.getLocationOnScreen(location);

        int top = location[1];
        int bottom = location[1] + view.getHeight();

        result[0] = top;
        result[1] = bottom;

        return result;
    }
    public void setYtitle(String title){
        yzhouTitle = title;
    }

    public void clearDataPoints(){
        dataPoints.clear();
        dataQueue.clear();
        timeStamps.clear();
        invalidate();
    }

    /** 设置Y轴范围 */
    public void setYRange(int min, int max) {
        minYvalue = min;
        maxYvalue = max;
        invalidate();

    }

    private void init() {
        yzhouTitle="";
        maxYvalue=10;
        minYvalue=-10;
        // 初始化网格画笔
        gridPaint = new Paint();
        gridPaint.setColor(Color.BLACK);
        gridPaint.setStrokeWidth(1f);
        gridPaint.setStyle(Paint.Style.STROKE);
        gridPaint.setAlpha(80); // 半透明

        // 初始化坐标轴画笔
        axisPaint = new Paint();
        axisPaint.setColor(Color.BLACK);
        axisPaint.setStrokeWidth(2f);
        axisPaint.setStyle(Paint.Style.STROKE);

        // 初始化波形画笔
        wavePaint = new Paint();
        wavePaint.setColor(Color.BLUE);
        wavePaint.setStrokeWidth(3f);
        wavePaint.setStyle(Paint.Style.STROKE);
        wavePaint.setAntiAlias(true);

        // 初始化文本画笔
        textPaint = new Paint();
        textPaint.setColor(Color.BLACK);
        textPaint.setTextSize(20f);
        textPaint.setAntiAlias(true);

        // 初始化竖向标题画笔
        verticalTitlePaint = new Paint();
        verticalTitlePaint.setColor(Color.BLACK);
        verticalTitlePaint.setTextSize(30f);
        verticalTitlePaint.setAntiAlias(true);
        verticalTitlePaint.setTextAlign(Paint.Align.CENTER);
        // 初始化一些随机数据
//        long currentTime = System.currentTimeMillis();
//        for (int i = 0; i < MAX_POINTS; i++) {
//            dataPoints.add(0f);
//            timeStamps.add(currentTime - (MAX_POINTS - i) * UPDATE_INTERVAL);
//        }
    }

    /** 将数据值映射到Y坐标 */
    private float mapY(float value) {
        float top = paddingTop + chartHeight*0.2f;
        float bottom = paddingTop + chartHeight;
        return bottom-((bottom-top)*(minYvalue-value)/ (float)(minYvalue-maxYvalue));
    }
    public void addDataPoint(float value) {
        // 添加新数据点和时间戳
        dataQueue.add(value);
       // timeStamps.add(System.currentTimeMillis());

        // 移除最旧的数据点
//        if (dataPoints.size() > MAX_POINTS) {
//            dataPoints.remove(0);
//            timeStamps.remove(0);
//        }
//
//        invalidate(); // 请求重绘
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 绘制白色背景
        canvas.drawColor(Color.WHITE);
        int width = getWidth();
        int height = getHeight();
        chartWidth = width - paddingLeft - paddingRight;
        chartHeight = height - paddingTop - paddingBottom;
        int[] pos = getViewTopAndBottom(this);
        topPixel = pos[0];
        bottonPixel = pos[1];
        System.out.println("canvossss5"+"Top = " + topPixel + "px, Bottom = " + bottonPixel + "px");
        // 绘制网格线 - 水平线
        for (int i = 0; i <5; i++) {
            float ratio = i / 5.0f;
            float y = paddingTop + chartHeight * (1 - ratio);
            canvas.drawLine(paddingLeft, y, width - paddingRight, y, gridPaint);

            // 绘制Y轴刻度 - 横向显示
            Integer label = minYvalue+i*(maxYvalue-minYvalue)/4;
            canvas.drawText(label.toString(), paddingLeft - 40, y + 10, textPaint);
        }

        // 绘制纵向网格线 - 每秒一条，共5条
        if (!timeStamps.isEmpty()) {
            long startTime = timeStamps.get(0);
            long endTime = timeStamps.get(timeStamps.size() - 1);
            long timeRange = endTime - startTime;

            // 绘制5条纵向网格线（每秒一条）
            for (int i = 0; i < 5; i++) {
                float x = paddingLeft + chartWidth * i / 5.0f;

                // 确保x在图表范围内
                if (x >= paddingLeft && x <= width - paddingRight) {
                    canvas.drawLine(x, paddingTop, x, height - paddingBottom, gridPaint);

                    // 计算对应的时间
                   // long timeAtGrid = startTime + (long)(timeRange * i / 5.0);
                    long timeAtGrid = startTime + i * 1000L;
                    // 绘制时间标签
                    Date date = new Date(timeAtGrid);
                    String timeLabel = timeFormat.format(date);
                    canvas.drawText(timeLabel, x - 40, height - paddingBottom + 40, textPaint);
                }
            }
        }
        // 绘制坐标轴
        canvas.drawLine(paddingLeft, paddingTop, paddingLeft, height - paddingBottom, axisPaint); // Y轴
        canvas.drawLine(paddingLeft, height - paddingBottom, width - paddingRight, height - paddingBottom, axisPaint); // X轴

        // 绘制波形
        if (dataPoints.size() > 1 && !timeStamps.isEmpty()) {
            long startTime = timeStamps.get(0);
            long endTime = timeStamps.get(timeStamps.size() - 1);
            long timeRange = endTime - startTime;

            Path path = new Path();

            // 移动到第一个点
            float firstX = paddingLeft;
            float firstY = mapY(dataPoints.get(0));
            path.moveTo(firstX, firstY);

            // 连接所有数据点
            for (int i = 1; i < dataPoints.size(); i++) {
                float x = paddingLeft + chartWidth * (timeStamps.get(i) - startTime) / (float) timeRange;
              // float y = paddingTop + chartHeight * (1 - dataPoints.get(i));
                float y =mapY(dataPoints.get(i));
                path.lineTo(x, y);
            }

            canvas.drawPath(path, wavePaint);
        }

        // 绘制标题
        // 绘制Y轴标题 - 纵向显示
        canvas.save();
        canvas.translate(10, paddingTop + chartHeight / 2);
        canvas.rotate(-90);
        canvas.drawText(yzhouTitle, 0, 30, verticalTitlePaint);
        canvas.restore();
        //canvas.drawText("时间", width / 2 - 30, height +10, textPaint);
    }
}